import 'package:flutter/material.dart';
import 'package:shenling_logistics/utils/eventBus.dart';
import 'package:shenling_logistics/utils/http.dart';
import 'package:shenling_logistics/utils/toast.dart';
import 'package:shenling_logistics/utils/token.dart';

class LoginPage extends StatefulWidget {
  const LoginPage({super.key});

  @override
  State<LoginPage> createState() => _LoginPageState();
}

class _LoginPageState extends State<LoginPage> {
  // 定义2个控制器
  final TextEditingController _usernameController = TextEditingController();
  final TextEditingController _passwordController = TextEditingController();
  bool _isObscured = true; // 初始状态为隐藏
  // 方便登录，定义账号和密码
  final String _username = 'hongli888';
  final String _password = '12345678';

  @override
  void initState() {
    super.initState();
    // 用户进入登录页，回写账号和密码
    setState(() {
      _usernameController.text = _username;
      _passwordController.text = _password;
    });
  }

  // 定义登录方法
  _loginSubmit() async {
    // 获取用户输入的账号和密码
    String username = _usernameController.text;
    String pwd = _passwordController.text;
    // 提交前校验 不能为空
    if (username.isEmpty || pwd.isEmpty)
      return ToastUtil.showError('用户名或密码不能为空');
    // 调用登录接口
    try {
      final res = await http.post('/driver/login/account', {
        'account': username,
        'password': pwd,
      });
      if (res['code'] != 200) return ToastUtil.showError(res['message']);
      // 将token存储本地
      TokenManager().saveToken(res['data']);
      // 登录成功后，通知刷新数据
      eventBus.fire(LoginSuccessEvent());
      // 提示用户登录成功
      ToastUtil.showSuccess('登录成功');
      // 返回到上一页
      Navigator.pop(context);
    } catch (e) {
      ToastUtil.showError('登录出现网络错误');
    }
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      backgroundColor: Colors.white,
      body: Column(
        children: [
          // 标题文本
          Container(
            margin: EdgeInsets.only(top: 30),
            width: MediaQuery.of(context).size.width,
            child: Text(
              '神领快递',
              textAlign: TextAlign.center,
              style: TextStyle(fontSize: 18, fontWeight: FontWeight.w600),
            ),
          ),
          SizedBox(height: 50),
          Container(
            padding: EdgeInsets.only(left: 32, right: 17),
            child: Row(
              children: [
                Text(
                  '账号登录',
                  style: TextStyle(fontSize: 24, fontWeight: FontWeight.w600),
                ),
                Spacer(),
                //右侧
                Row(
                  children: [
                    Text(
                      '手机号登录',
                      style: TextStyle(
                        fontSize: 16,
                        fontWeight: FontWeight.w500,
                        color: Colors.red,
                      ),
                    ),
                    SizedBox(width: 7),
                    // 三角图标
                    Icon(Icons.play_arrow, size: 14, color: Colors.red),
                  ],
                ),
              ],
            ),
          ),
          SizedBox(height: 40),
          // 账号输入框
          Container(
            padding: EdgeInsets.only(left: 33, right: 33),
            height: 60,
            child: TextField(
              controller: _usernameController,
              keyboardType: TextInputType.name,
              style: TextStyle(fontSize: 16),
              decoration: InputDecoration(
                hintText: '请输入账号',
                // 边框样式  未聚焦状态
                enabledBorder: UnderlineInputBorder(
                  borderSide: BorderSide(
                    color: Color.fromARGB(255, 235, 233, 233),
                  ),
                ),
              ),
            ),
          ),
          // 账号密码
          Container(
            padding: EdgeInsets.only(left: 33, right: 33),
            height: 60,
            child: TextField(
              controller: _passwordController,
              obscureText: _isObscured, // 隐藏输入内容，用 * 或 • 替代显示
              keyboardType: TextInputType.visiblePassword,
              style: TextStyle(fontSize: 16),
              decoration: InputDecoration(
                hintText: '请输入密码',
                // 边框样式  未聚焦状态
                enabledBorder: UnderlineInputBorder(
                  borderSide: BorderSide(
                    color: Color.fromARGB(255, 235, 233, 233),
                  ),
                ),
                suffixIcon: IconButton(
                  icon: Icon(
                    _isObscured ? Icons.visibility_off : Icons.visibility,
                  ),
                  onPressed: () {
                    setState(() => _isObscured = !_isObscured);
                  },
                ),
              ),
            ),
          ),
          SizedBox(height: 50),

          // 登录按钮
          Container(
            padding: EdgeInsets.only(left: 33, right: 33),
            width: MediaQuery.of(context).size.width,
            height: 50,
            child: ElevatedButton(
              onPressed: () {
                // 调用登录方法
                _loginSubmit();
              },
              style: ButtonStyle(
                backgroundColor: WidgetStateProperty.all(Colors.red),
              ),
              child: Text('登录', style: TextStyle(color: Colors.white)),
            ),
          ),
        ],
      ),
    );
  }
}
